package com.string.actortv.receiver;

import android.app.AlertDialog;
import android.content.*;
import android.os.Process;
import android.os.*;
import android.view.View;
import com.string.actortv.APPApplication;
import com.string.actortv.R;
import com.string.actortv.dto.UpdateInfoModel;
import com.string.actortv.dto.UpdateInformation;
import com.string.actortv.service.UpdateService;
import com.string.actortv.util.CacheHelper;
import com.string.actortv.view.DownLoadProgressbar;
import org.jetbrains.annotations.NotNull;

import java.io.File;

import static android.content.Context.BIND_AUTO_CREATE;

/**
 * 版本更新升级 广播接受者
 */
public class UpdateReceiver extends BroadcastReceiver {
    public static final String UPDATE_ACTION = "string_actor-tv";
    private AlertDialog.Builder mDialog;
    private boolean isShowDialog;
    private DownLoadProgressbar dView;
    private View view1;
    private AlertDialog show;
    private UpdateService.DownLoadBinder downLoadBinder;

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NotNull Message msg) {
            switch (msg.what) {
                case 0:
                    dView.setCurrentValue(msg.getData().getInt("num"));
                    break;
                case 1:
                    show.dismiss();
                    break;
                default:
            }
            return true;
        }
    });

    private final ServiceConnection connection = new ServiceConnection() {
        /**
         * 服务解除绑定时候调用
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub

        }

        /**
         * 绑定服务的时候调用
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            downLoadBinder = (UpdateService.DownLoadBinder) service;
            UpdateService service2 = downLoadBinder.getService();
            /**
             * 实现回调，得到实时刷新的数据
             */
            service2.setServiceCallback(new UpdateService.ServiceCallback() {
                @Override
                public void setCurrentValue(int num) {
                    Message message = new Message();
                    message.what = 0;
                    Bundle bundle = new Bundle();
                    bundle.putInt("num", num);
                    message.setData(bundle);
                    handler.sendMessage(message);
                }

                @Override
                public void dismissDialog() {
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }
            });
        }
    };

    public UpdateReceiver() {
    }

    public UpdateReceiver(boolean isShowDialog) {
        super();
        this.isShowDialog = isShowDialog;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        //当然了，这里也可以直接new处hashmap
        UpdateInfoModel model = (UpdateInfoModel) CacheHelper.CACHE
                //就是一个标志
                .get(CacheHelper.KEY_APP_UPDATE);
        try {
            /**
             * 获取到当前的本地版本
             */
            UpdateInformation.localVersion = APPApplication.getAppVersionCode();
            /**
             * 获取到当前的版本名字
             */
            UpdateInformation.versionName = APPApplication.getAppVersionName();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //app名字
        UpdateInformation.appname = APPApplication.getInstance()
                .getResources().getString(R.string.app_name);
        //服务器版本
        UpdateInformation.serverVersion = Integer.parseInt(model
                .getServerVersion());
        //服务器标志
        UpdateInformation.serverFlag = Integer.parseInt(model.getServerFlag());
        //升级地址
        UpdateInformation.updateurl = model.getUpdateurl();
        //升级信息
        UpdateInformation.upgradeinfo = model.getUpgradeinfo();

        //检查版本
        checkVersion(context);

    }

    /**
     * 检查版本更新
     *
     * @param context
     */
    public void checkVersion(Context context) {
        if (UpdateInformation.localVersion < UpdateInformation.serverVersion) {
            // 需要进行更新
            update(context);
        } else {
            if (isShowDialog) {
                //没有最新版本，不用升级
                noNewVersion(context);
            }
            clearUpateFile(context);
        }
    }

    /**
     * 进行升级
     *
     * @param context
     */
    private void update(Context context) {
//        if (UpdateInformation.serverFlag == 1) {
//            // 官方推荐升级
//            if (UpdateInformation.localVersion < UpdateInformation.lastForce) {
//                //强制升级
//                forceUpdate(context);
//            } else {
//                //正常升级
//                normalUpdate(context);
//            }
//
//        } else if (UpdateInformation.serverFlag == 2) {
        // 官方强制升级
        forceUpdate(context);
//        }
    }

    /**
     * 没有新版本
     *
     * @param context
     */
    private void noNewVersion(final Context context) {
        mDialog = new AlertDialog.Builder(context);
        mDialog.setTitle("版本更新");
        mDialog.setMessage("当前为最新版本");
        mDialog.setNegativeButton("确定", (dialog, which) -> dialog.dismiss()).create().show();
    }

    /**
     * 强制升级 ，如果不点击确定升级，直接退出应用
     *
     * @param context
     */
    private void forceUpdate(final Context context) {
        mDialog = new AlertDialog.Builder(context);
        mDialog.setTitle("版本更新");
        mDialog.setMessage(UpdateInformation.upgradeinfo);

        mDialog.setPositiveButton("确定", (dialog, which) -> {
            Intent mIntent = new Intent(context, UpdateService.class);
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mIntent.putExtra("appname", UpdateInformation.appname);
            mIntent.putExtra("appurl", UpdateInformation.updateurl);
            mIntent.putExtra("forceFlag", 2);
            //弹框开始下载
            view1 = View.inflate(context, R.layout.progress_main, null);
            dView = view1.findViewById(R.id.dp_game_progress);
            dView.setMaxValue(100);

            mDialog = new AlertDialog.Builder(context);
            mDialog.setTitle("下载中")
                    .setIcon(R.drawable.ic_launcher)
                    .setView(view1)
                    .create();
            show = mDialog.show();
            //启动服务
            context.bindService(mIntent, connection, BIND_AUTO_CREATE);
            context.startService(mIntent);
        }).setNegativeButton("退出", (dialog, which) -> {
            // 直接退出应用
            Process.killProcess(Process.myPid());
        }).setCancelable(false).create().show();
    }

    /**
     * 正常升级，用户可以选择是否取消升级
     *
     * @param context
     */
    private void normalUpdate(final Context context) {
        mDialog = new AlertDialog.Builder(context);
        mDialog.setTitle("版本更新");
        mDialog.setMessage(UpdateInformation.upgradeinfo);
        mDialog.setPositiveButton("确定", (dialog, which) -> {
            Intent mIntent = new Intent(context, UpdateService.class);
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //传递数据
            mIntent.putExtra("appname", UpdateInformation.appname);
            mIntent.putExtra("appurl", UpdateInformation.updateurl);
            mIntent.putExtra("forceFlag", 1);
            context.startService(mIntent);
        }).setNegativeButton("取消", (dialog, which) -> dialog.dismiss()).create().show();
    }

    /**
     * 清理升级文件
     *
     * @param context
     */
    private void clearUpateFile(final Context context) {
        File updateDir;
        File updateFile;
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {
            updateDir = new File(Environment.getExternalStorageDirectory(),
                    UpdateInformation.downloadDir);
        } else {
            updateDir = context.getFilesDir();
        }
        updateFile = new File(updateDir.getPath(), context.getResources()
                .getString(R.string.app_name) + ".apk");
        if (updateFile.exists()) {
            updateFile.delete();
        }
    }
}
